import user from '@/content/api/user'
import moment from 'moment';
let lastMessageTime = null

export class Message {
    constructor() {}

    static getPostMessage() {
        if (localStorage.isOffline !== "false") {
            return
        }
        window.postMessageInterval || clearInterval(window.postMessageInterval)
        window.postMessageInterval = setInterval(() => {
            user.getAllPostMessage().then(res => {
                if (res.code === '0') {
                    let refreshMessagesArry = res.returnValue
                    if (!refreshMessagesArry) return
                    if (!lastMessageTime) {
                        lastMessageTime = moment(refreshMessagesArry[refreshMessagesArry.length - 1].modifyTime, 'YYYY年MM月DD日 HH:mm:ss')
                    } else {
                        let nowTime = moment(refreshMessagesArry[refreshMessagesArry.length - 1].modifyTime, 'YYYY年MM月DD日 HH:mm:ss');
                        if (lastMessageTime < nowTime) {
                            let noAllread = res.returnValue.filter(message => {
                                return message.isRead === '0'
                            })
                            let haveNewMessage = new BroadcastChannel('push-messgae-has-been-updated')
                            haveNewMessage.postMessage({
                                tip: '您有新的消息待查看',
                                updateNum: noAllread.length
                            })
                            console.log("发送消息", noAllread.length)
                        }
                        lastMessageTime = nowTime;
                    }
                }
            })
        }, 10 * 60 * 1000);
    }
}